package cn.mesmile.thread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author zb
 * @date 2020/12/29 16:31
 * @Description
 */
public class ThreadPoolTest {
    // 这里加上 volatile 关键字 【volatile满足线程之间可见性和防止指令重排】
    public volatile static Integer count = 0;

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        List<String> stringList = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
        // 创建一个线程池   开启【5】个线程
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        ExecutorCompletionService<Integer> service = new ExecutorCompletionService<>(executorService);

        // ①.建立stringList.size()个计数
        CountDownLatch latch = new CountDownLatch(stringList.size());
        Future<Integer> submit = null;
        for (String str : stringList) {
            submit = service.submit(new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                        Thread.sleep(1000L);
                        System.out.println(">>>>>>>>>>>>>>>>>>  :" + str + "  " + Thread.currentThread().getName());
                        count++;
                        // ②.线程完成一次减去 1
                        latch.countDown();
                        return count;
                }
            });
        }
        try {
            // ③.直到数字被减为 0 才执行这个方法
            latch.await();
            // 这里最终的到的结果[可能不准确]
            System.out.println("submit.get() = " + submit.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("count = " + count);
        executorService.shutdown();
        System.out.println("(end - start) = " + (end - start));

    }
}
